/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 * @version 1.0
 */
package shop.controller.manage.fund;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.BaseController;
import shop.core.common.bean.JSONResult;
import shop.core.common.bean.ManageContainer;
import shop.core.common.dao.page.PagerModel;
import shop.services.manage.fund.FundService;
import shop.services.manage.fund.bean.Fund;
import shop.services.manage.offlineAccount.OfflineAccountService;
import shop.services.manage.organize.OrganizeService;
import shop.services.manage.organize.bean.Organize;
import shop.services.manage.system.bean.User;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**   
 * @类名称：FundAction      
 * @创建人：Ltz   
 * @创建时间：2017-07-16 下午12:31:52      
 * @版本号：1.0
 * @描述：     
 */
@Controller
@RequestMapping("/manage/fund/")
public class FundAction extends BaseController<Fund> {
    private static final Logger logger = LoggerFactory.getLogger(FundAction.class);
    @Autowired
    private FundService fundService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private OfflineAccountService offlineAccountService;
    private static final String page_toList = "/manage/fund/donationList";
    private static final String page_toCheck = "/manage/fund/cashCheck";
    private static final String page_toOrganizeList = "/manage/fund/donationOrganizeList";
    private static final String page_toOrganizeDetails = "/manage/fund/cashOrganizeDetails";
    public FundService getService() {
        return fundService;
    }

    private FundAction(){
        super.page_toList = page_toList;
        super.page_toAdd = null;
        super.page_toEdit = null;
    }


    /**
     * 跳转到捐赠列表页面（机构）
     * @return
     */
    @RequestMapping("toOrganizeList")
    public String toOrganizeList() {
        return page_toOrganizeList;
    }

    /**
     * 跳转到审核列表页面（admin）
     * @return
     */
    @RequestMapping("toCheck")
    public String toCheck() {
        return page_toCheck;
    }

    /**
     * 跳转到审核列表页面（机构）
     * @return
     */
    @RequestMapping("toOrganizeDetails")
    public String toOrganizeDetails() {
        return page_toOrganizeDetails;
    }


    /**
     * 查询提现记录方法
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @Override
    @RequestMapping("loadData")
    @ResponseBody
    public PagerModel loadData(HttpServletRequest request, Fund e) {
        int offset = 0;
        int pageSize = 10;
        if (e.getPayee()!=null){
            e.setPayAccount(e.getPayee());
            e.setOrganizeName(e.getPayee());
        }
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize organize=new Organize();
        organize.setPrincipalPhone(user.getUsername());
        organize=organizeService.selectOne(organize);
        PagerModel pager = null;
        if(!user.getRid().equals("1")){
            if(organize.getStatus().equals("3")){
                return pager;
            }else{
                e.setOrganizeID(organize.getId());
                pager = getService().selectPageList(e);
                pager.setRecordsTotal(pager.getTotal());
                pager.setRecordsFiltered(pager.getTotal());
            }
        }else{
            pager = getService().selectPageList(e);
            pager.setRecordsTotal(pager.getTotal());
            pager.setRecordsFiltered(pager.getTotal());
        }
        return pager;
    }

    /**
     * 提现申请方法
     * @param request
     * @param fund
     * @return
     * @throws Exception
     */
    @Override
    @RequestMapping(value = "insertJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertJson(HttpServletRequest request, @ModelAttribute("fund") Fund fund) throws Exception {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize organize=new Organize();
        organize.setPrincipalPhone(user.getUsername());
        organize=organizeService.selectOne(organize);
        if(!organize.getStatus().equals("3")){
            if(Integer.parseInt(fund.getMoney())<=Integer.parseInt(organize.getUnCash())){
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                fund.setApplyDate(df.format(new Date()));
                fund.setOrganizeID(organize.getId());
                fund.setApplicant(user.getNickname());
                fund.setStatus("1");
                fundService.insert(fund);
                organize.setUnCash(String.valueOf(Integer.parseInt(organize.getUnCash())-Integer.parseInt(fund.getMoney())));
                organize.setCash(String.valueOf(Integer.parseInt(organize.getCash()) + Integer.parseInt(fund.getMoney())));
                organizeService.update(organize);
            }else{
                jsonResult.setMessage("提现余额不足，请修改提现额度！");
                jsonResult.setSuccess(false);
                return jsonResult;
            }
        }else{
            jsonResult.setMessage("您还未进行认证，无法进行提现操作！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
        return jsonResult;
    }

    /**
     * 提现审核方法
     * @param request
     * @param fund
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "checkJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult checkJson(HttpServletRequest request, @ModelAttribute("fund") Fund fund) throws Exception {
        jsonResult = new JSONResult();
        String status=fund.getStatus();
        fund=fundService.selectOne(fund);
        Organize organize=new Organize();
        organize.setId(fund.getOrganizeID());
        organize=organizeService.selectOne(organize);
        fund.setStatus(status);
        getService().update(fund);
        if(fund.getStatus().equals("3")){
            organize.setUnCash(String.valueOf(Integer.parseInt(organize.getUnCash()) + Integer.parseInt(fund.getMoney())));
            organize.setCash(String.valueOf(Integer.parseInt(organize.getCash()) - Integer.parseInt(fund.getMoney())));
            organizeService.update(organize);
        }
        return jsonResult;
    }

}
